package struts.action;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import struts.actionform.ClientLoginForm;
import ejb.bl.MusicStoreBLRemote;

public class ClientLoginAction extends Action {
	@EJB(name = "MusicStoreStalessBean")
	private MusicStoreBLRemote MusicStoreBLBean;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		// Create object of ActionMesssages
		ActionMessages errors = new ActionMessages();

		// creating object of UserLoginForm
		ClientLoginForm objForm = (ClientLoginForm) form;

		// get userid from objForm
		int userid = objForm.getUserid();

		// get password from objForm
		String strPassword = objForm.getPassword();

		// check user is valid or not
		try {
			//InitialContext ic = new InitialContext();
			//MusicStoreBLBean = (MusicStoreBLRemote) ic
			//		.lookup("java:global/IMusicStore/MusicStoreStalessBean");
			boolean loginStatus = MusicStoreBLBean.checkClientLogin(userid,
					strPassword);

			if (loginStatus == true) {
				// create new session object
				HttpSession session = request.getSession();

				// setting attributes to the session object
				session.setAttribute("UserID", String.format("%d", userid));
				return mapping.findForward("success");
			} else {
				errors.add("login", new ActionMessage("error.login.invalid"));
				// saving error object
				saveErrors(request, errors);

				return mapping.findForward("fail");
			}
		} catch (RuntimeException e) {
			throw e;
		}
	}
}
